package ccm.itesm.mx.servicios;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;

public class AndroidDAO {

   private static final String BASE_DE_DATOS = "donjuan.db";
   private static final int VERSION = 1;
   private static final String UN_TABLA = "contactos";
   
   OpenHelper open;

   private SQLiteDatabase db;

   private SQLiteStatement insertStmt;
   private static final String INSERT = 
	   "insert into "  + UN_TABLA + "(nombre, telefono) values (?,?)";

   public AndroidDAO(Context context) {
	   open = new OpenHelper(context);
	   db = open.getWritableDatabase();
	   insertStmt = db.compileStatement(INSERT);
   }

   public long insert(String name, String phone) {
	   this.insertStmt.bindString(1, name);
	   this.insertStmt.bindString(2, phone);
	   return this.insertStmt.executeInsert();
	   
   }
   
   public void update(long idupdate, String nombre) {
	   ContentValues updateValues = new ContentValues();
	   updateValues.put("nombre", nombre);
	   db.update(UN_TABLA, updateValues, "id=" + idupdate,null);
	   
   }

   public void deleteAll() {
	   db.delete(UN_TABLA, null, null);
   }

   public String selectPrimero() {
	   Cursor c = this.db.query(UN_TABLA, new String[]{"id","telefono"}, null, null, null, null, "nombre desc");
	   c.moveToFirst();
	   String primero = c.getString(0);
	   return primero;
   }
   public List<String> selectAll() {
      List<String> list = new ArrayList<String>();
      Cursor c = this.db.query(UN_TABLA, new String[]{"nombre","telefono"}, null, null, null, null, "nombre desc");
      if(c.moveToFirst()){
    	  do{
    		  list.add(c.getString(0));
    		  
    	  }while(c.moveToNext());
      }      
      return list;
   }

   static class OpenHelper extends SQLiteOpenHelper {

      OpenHelper(Context context) {
         super(context, BASE_DE_DATOS, null, VERSION);
      }

      @Override
      public void onCreate(SQLiteDatabase db) {
    	  db.execSQL("CREATE TABLE " + UN_TABLA + 
    			  " (id INTEGER PRIMARY KEY, nombre TEXT, telefono TEXT)");
      }

      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    	  db.execSQL(" DROP TABLE IF EXISTS "+ UN_TABLA);
    	  onCreate(db);
      }
   }
}

